#!/usr/bin/env python

from urlparse import urlparse

def get_hostname(url):
    obj = urlparse(url)
    return obj.netloc.split(':')[0]

def get_next_level_domain(hostname):
    components = hostname.split('.')
    return hostname if (len(components) < 3) else '.'.join(components[1:])

def get_num_components(domain):
    components = domain.split('.')
    return len(components)

def get_domain_subset(url, num):
    hostname = get_hostname(url)
    components = hostname.split('.')
    return '.'.join(components[-num:])

def match_hostnames(starting_url, this_url, span):
    if span:
        this_domain = get_domain_subset(this_url, starting_url.length_nld)
        return starting_url.next_level_domain == this_domain
    else:
        return starting_url.hostname == get_hostname(this_url)

class StartingURL(object):
    def __init__(self, url, debug=False):
        self.url = url
        self.hostname = get_hostname(self.url)
        self.next_level_domain = get_next_level_domain(self.hostname)
        self.length_nld = get_num_components(self.next_level_domain)
        if debug:
            print 'hostname: ', self.hostname
            print 'next_level_domain: ', self.next_level_domain
            print 'length_nld: ', self.length_nld

if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2: sys.exit()
    starting_url = StartingURL(sys.argv[1], debug=True)
